package gorillamux

import (
	"github.com/gorilla/mux"
	"net/http"
	"strings"
)

type Route struct {
	Name    string
	Method  string
	Pattern string
	// Auth        bool
	HandlerFunc http.HandlerFunc
}
type Routes []Route

//定义路由
var routes = Routes{
	Route{"index", "GET", "/", Index},
	Route{"user", "POST", "/user/login", UserLogin},
	Route{"user", "GET,POST", "/user/info", UserInfo},
}

var router *mux.Router

func NewRouter() *mux.Router {
	if router == nil {
		router = mux.NewRouter().StrictSlash(true)
	}
	//router := mux.NewRouter().StrictSlash(true)

	for _, route := range routes {
		var handler http.Handler = CorsHeader(route.HandlerFunc) //处理跨域问题

		router.
			Methods(strings.Split(route.Method, ",")...).
			Path(route.Pattern).
			Name(route.Name).
			Handler(handler)

		router.
			Methods("OPTIONS").
			Path(route.Pattern).
			Name("cors").
			Handler(CorsHeader(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				return
			})))
	}
	return router
}

//处理跨域问题
func CorsHeader(inner http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
		w.Header().Set("Access-Control-Allow-Credentials", "true")
		w.Header().Add("Access-Control-Allow-Method", "POST, OPTIONS, GET, HEAD, PUT, PATCH, DELETE")
		w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, X-HTTP-Method-Override,accept-charset,accept-encoding , Content-Type, Accept, Cookie")
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		inner.ServeHTTP(w, r)
	})

}
